package com.cwd.arm.inter.util;

import com.cwd.arm.common.enums.ExportFileEnum;
import com.cwd.arm.common.util.DateUtil;
import com.cwd.arm.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yan on 22-1-30.
 */
@Slf4j
public class ExportUtil {

    private static final String JXL_TEMP_PLATE_PATH = "jxl/template/";

    private static final ExportUtil INSTANCE = new ExportUtil();

    public static ExportUtil getInstance() {
        return INSTANCE;
    }

    public void exportExcel(HttpServletResponse response, Map<String, Object> bean, ExportFileEnum exportFileEnum) throws Exception {
        exportExcel(response, bean, exportFileEnum, null);
    }

    public void exportExcel(HttpServletResponse response, Map<String, Object> bean, ExportFileEnum exportFileEnum, Integer year) throws Exception {
        InputStream in = null;
        OutputStream out = null;
        try {
            //设置header
            String destFileName = exportFileEnum.getFileName() + "-" + DateUtil.dateToDateStr(new Date()) + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(destFileName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel");
            //转换数据
            bean.put("year", year);
            Context context = PoiTransformer.createInitialContext();
            if (bean != null) {
                for (String key : bean.keySet()) {
                    context.putVar(key, bean.get(key));
                }
            }
            //设置模板
            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            in = getClass().getClassLoader().getResourceAsStream(JXL_TEMP_PLATE_PATH + exportFileEnum.getTemplateName());
            out = response.getOutputStream();
            Transformer transformer = jxlsHelper.createTransformer(in, out);
            JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
            //设置静默模式，不报警告
//            evaluator.getJexlEngine().setSilent(true);
            //自定义功能
            Map<String, Object> funcs = new HashMap<>();
            funcs.put("f", new JxlsUtils());
            evaluator.getJexlEngine().setFunctions(funcs);
            //必须要这个，否者表格函数统计会错乱
            jxlsHelper.setUseFastFormulaProcessor(true).setProcessFormulas(true).processTemplate(context, transformer);
            out.flush();
        } catch (IOException e) {
            log.warn("ExportUtil:{}", e.getMessage(), e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("ExportUtil.in.close失败:{}", e.getMessage(), e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("ExportUtil.out.close失败::{}", e.getMessage(), e);
                }
            }
        }
    }

}
